/**
 * 
 */
package org.chungyan5.multiplenestingtagging.mobile;

import org.chungyan5.multiplenestingtagging.DbConn;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

/**
 * @author yan
 *
 */
public class ItemAttachTags extends ListActivity {
	
	private ListView listViewTags;
	private Cursor currentCursor = null;
	private SimpleCursorAdapter adapterTag;
	private long itemId;

    public void onCreate(Bundle savedInstanceState) {
    	
	    // show this Activity ====================================================
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.item_attach_tags);
	    
	    // get which Item ====================================================
	    Bundle bundle = this.getIntent().getExtras();
	    itemId = bundle.getLong("id");
	    
	    // prepare a Button for confirmed Tag(s) =================================
        Button buttonBackMain = (Button) findViewById(R.id.ButtonBackToMain);
        buttonBackMain.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent myIntent = new Intent();
				setResult(RESULT_OK, myIntent);
                finish();
			}
		});
	    
	    // config the ListView ================================================
	    listViewTags = getListView();
	    listViewTags.setItemsCanFocus(false);
	    listViewTags.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	    listViewTags.setCacheColorHint(0);
	
	    // background to get back all Tags fr. Db =================================
       new GetTagsTask().execute();
        
    }

	private class GetTagsTask extends AsyncTask<String, Void, String> {

		protected void onPreExecute() {
		}

		protected String doInBackground(final String... args) {
			Uri uriAttachedTags = Uri.withAppendedPath(MNTContentProvider.CONTENT_URI, MNTContentProvider.ITEM_ATTACHED_TAGS_PATH);
			currentCursor = managedQuery(uriAttachedTags, null, Long.toString(itemId), null, null);
			return null;
		}

		// can use UI thread here
		protected void onPostExecute(final String result) {

			startManagingCursor(currentCursor);
			adapterTag = new HandleAttachedTagsSimpleCursorAdapter(ItemAttachTags.this
					, R.layout.single_tag, currentCursor
	        		, new String[] { DbConn.TABLE_TAG_COL_TAG_NAME }
					, new int[] {R.id.listTagNames}
					, itemId);
			setListAdapter(adapterTag);
		}
	}

}
